package com.thz.houserental.domain.tenant;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thz.houserental.domain.house.HouseService;
import com.thz.houserental.infrastructure.exception.ParameterException;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
public class TenantServiceImpl
        extends ServiceImpl<TenantMapper, Tenant>
        implements TenantService {
    
    private final HouseService houseService;

    public TenantServiceImpl(@Lazy HouseService houseService) {
        this.houseService = houseService;
    }

    @Override
    public void checkByHouseId(String houseId, boolean shouldExist) {
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        tenantQueryWrapper.lambda()
                .eq(Tenant::getHouseId, houseId);

        Tenant tenant = this.baseMapper.selectOne(tenantQueryWrapper);
        if(!shouldExist && tenant != null) {
            throw new ParameterException(10701);
        } else if(shouldExist && tenant == null) {
            throw new ParameterException(10702);
        }
    }

    @Override
    public void register(Tenant tenant) {
        // 如果已经存在租户则不允许注册
        this.checkByHouseId(tenant.getHouseId(), false);
        
        // 房屋下线
        this.houseService.offLine(tenant.getHouseId());
        tenant.setId(null);
        this.save(tenant);
    }

    @Override
    public void checkOut(Tenant tenant) {
        // 如果房屋租户不存在，则退房失败
        this.checkByHouseId(tenant.getHouseId(), true);
        
        // 退房成功，上线房源
        this.houseService.onLine(tenant.getHouseId());

        // 删除
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        tenantQueryWrapper.lambda()
                .eq(Tenant::getHouseId, tenant.getHouseId())
                .eq(Tenant::getUserId, tenant.getUserId());
        this.remove(tenantQueryWrapper);
    }
}
